package com.yunhe.commons.util;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;

/**
 * 从config.properties  中拿值
 * @author tianxuan
 * @Time 2016/4/22
 */
public class PropertiesHandler {

    private Properties properties;   //要读取的properties

    /**
     *   创建读取priperties文件的处理器
     * @param fileName  要被读取的properites 文件名字
     */
    public PropertiesHandler(String fileName) {
        Reader reader = null;
        fileName = (null == fileName || fileName.isEmpty()) ? "config" : fileName;
        try {
            reader = new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName + ".properties"));
            properties = new Properties();
            properties.load(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Properties getProperties() {
        return properties;
    }

    /**
     * 从properties 读取值
     * @param key
     * @return
     */
    public String readValue(String key) {
        String rtVal = null;
        try {
            rtVal = properties.getProperty(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtVal;
    }




    /**
     * 将properites 写出到配置文件
     * @param pro
     * @param fileName
     * @param comments
     */
    public static void writeProperties(Properties pro, String fileName, String comments){
        try {
            FileOutputStream out = new FileOutputStream(Thread.currentThread().getContextClassLoader().getResource(fileName + ".properties").getFile());
            pro.store(out, comments);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
